//
//  GoodsReleasedController.m
//  BestPurchase
//
//  Created by ZSMAC on 2018/10/10.
//  Copyright © 2018年 张帅. All rights reserved.
//

#import "GoodsReleasedController.h"
#import "TopSelectedPicView.h"
#import "GoodsModel.h"
#import "ReleaseCell.h"
#import "ReleaseCellModel.h"
#import "ZLPhotoActionSheet.h"
#import "ZLDefine.h"
#import "GoodsReleasedNavBar.h"

@interface GoodsReleasedController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,retain)TopSelectedPicView  *headVaiew;
@property(nonatomic,retain) GoodsModel * goodsModel;
@property(nonatomic,retain) GoodsReleasedNavBar * navBar;
@end

@implementation GoodsReleasedController
-(instancetype)init {
    self=[super init];
    if (self) {
        self.goodsModel = [[GoodsModel alloc] init];
        self.title=@"商品发布";
        _dataArray=[[NSMutableArray alloc] init];
        self.hidesBottomBarWhenPushed=YES;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!self.navigationController.navigationBarHidden) {
        self.navigationController.navigationBarHidden=YES;
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    @WeakObj(self);
    if (self.goodsModel.goodsType.length==0) {
        [_navBar selectedType];
    }
    [_navBar setSetectTypeBlock:^(NSString *typeStr) {
        selfWeak.goodsModel.goodsType=typeStr;
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self UIconfigur];
   
}

- (void)initData {
    _dataArray=[[NSMutableArray alloc] init];
    for (int i=0; i<3; i++) {
        ReleaseCellModel *model = [[ReleaseCellModel alloc] init];
        if (i==0) {
            model.showType=Show_Price_Type;
        } else if (i==1) {
             model.showType=Show_Title_Type;
            model.placeholderStr=@"请输入商品标题";
        } else if (i==2) {
            model.showType=Show_Add_Type;
        }
        [_dataArray addObject:model];
    }
    [_tableView reloadData];
}
- (void)UIconfigur {
   
    self.headVaiew = [[TopSelectedPicView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-50) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.estimatedSectionFooterHeight=0;
    _tableView.estimatedSectionHeaderHeight=0;
    _tableView.tableHeaderView=self.headVaiew;
    _tableView.backgroundColor=[UIColor whiteColor];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self addBottomBar];
    
    _navBar = [[GoodsReleasedNavBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavBarHeight)];
    [self.view addSubview:_navBar];
}
-(void)addBottomBar {
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-NavBarHeight, SCREEN_WIDTH, 50)];
    footView.backgroundColor=[UIColor whiteColor];
    UIButton * releaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    releaseBtn.frame=CGRectMake(15, 10, SCREEN_WIDTH-30, 40);
    [releaseBtn setTitle:@"发布" forState:UIControlStateNormal];
    releaseBtn.backgroundColor=themeColor;
    releaseBtn.layer.cornerRadius=5;
    releaseBtn.layer.masksToBounds=YES;
    [releaseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [releaseBtn addTarget:self action:@selector(releaseBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:releaseBtn];
    [self.view addSubview:footView];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat bili =scrollView.contentOffset.y/NavBarHeight;
    _navBar.currentAlpha=bili;
    NSLog(@"scrollView.contentOffset.y %f %f",scrollView.contentOffset.y,bili);
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"ReleaseCell";
    ReleaseCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[ReleaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    ReleaseCellModel *model = self.dataArray[indexPath.row];
    cell.indexPath=indexPath;
    [cell setGetCellHeight:^(CGFloat cellHeight) {
        model.cellHeight=cellHeight;
    }];
      @WeakObj(self);
    [cell setEditorRefreshCellHeightBolck:^(CGFloat cellNewHeight) {
        [selfWeak.tableView beginUpdates];
        model.cellHeight=cellNewHeight;
        [selfWeak.tableView endUpdates];
    }];
    
    [cell setAddContentBlock:^{
        [selfWeak addContent];
    }];
    
    [cell setDeleteBlock:^(NSIndexPath *indexPath) {
        [selfWeak.dataArray removeObjectAtIndex:indexPath.row];
        [selfWeak.tableView reloadData];
    }];
    
    cell.cellModel=model;
    return cell;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   ReleaseCellModel *model = self.dataArray[indexPath.row];
    return model.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
#pragma mark 添加内容
- (void)addContent{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择添加类型" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
   @WeakObj(self);
    UIAlertAction *textAction=[UIAlertAction actionWithTitle:@"添加文字描述" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ReleaseCellModel *model = [[ReleaseCellModel alloc] init];
        model.showType=Show_textContent_Type;
        model.placeholderStr=@"请输入详情描述";
        [selfWeak.dataArray insertObject:model atIndex:selfWeak.dataArray.count-1];
        [selfWeak.tableView reloadData];
    }];
   
    UIAlertAction *imageAction=[UIAlertAction actionWithTitle:@"添加详情图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZLPhotoActionSheet * a = [selfWeak getPas];
        [a showPhotoLibrary];
    }];
    [alert addAction:cancelAction];
    [alert addAction:imageAction];
    [alert addAction:textAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 发布
- (void)releaseBtnClicked:(UIButton *)btn {
    BmobUser *user= [BmobUser currentUser];
    if (user==nil) {
        [ZSProgressHUD showDpromptText:@"请登录后发布"];
        return;
    }
    [ZSProgressHUD showHUDShowText:@"发布中..."];
   self.goodsModel.listName=Goods_list_Name;
//   self.goodsModel.author = user;
   [self uploadTopImages];
}
#pragma mark 上传轮播图图片
- (void)uploadTopImages {
    @WeakObj(self);
    [MPublicManager batchUploadImages:self.headVaiew.imageList proportion:NO successfulBlock:^(NSArray *imageUrls) {
        [selfWeak.goodsModel.topRollingImages addObjectsFromArray:imageUrls];
        [selfWeak uploadDetailsImages];
    } errorBlock:^{
        [ZSProgressHUD showDpromptText:@"图片上传失败"];
    }];
    
}
#pragma mark 上传详情图片
- (void)uploadDetailsImages {
    NSMutableArray *detailImages = [[NSMutableArray alloc] init];
    for (ReleaseCellModel *cellModel in self.dataArray) {
        if (cellModel.showType==Show_Image_Type) {
            [detailImages addObject:cellModel.image];
        }
    }
    if (detailImages.count==0) {
        [self submitDataWithDetailImageUrls:nil];
    } else {
        @WeakObj(self);
        //上传详情图片
        [MPublicManager batchUploadImages:detailImages proportion:YES successfulBlock:^(NSArray *imageUrls) {
            [selfWeak submitDataWithDetailImageUrls:imageUrls];
        } errorBlock:^{
            [ZSProgressHUD showDpromptText:@"图片上传失败"];
        }];
    }
}

- (void)submitDataWithDetailImageUrls:(NSArray *)detailImageUrls {
    int i=0;
    for (ReleaseCellModel *cellModel in self.dataArray) {//配置数据
        if (cellModel.showType==Show_Price_Type) {
            self.goodsModel.UnitPrice=cellModel.content;//价格
        } else if (cellModel.showType==Show_Title_Type) {
            self.goodsModel.title=cellModel.content;//标题
        } else if (cellModel.showType==Show_textContent_Type) {
            [self.goodsModel.details addObject:cellModel.content];
        } else if (cellModel.showType==Show_Image_Type) {
            if (detailImageUrls!=nil && detailImageUrls.count!=0) {
                [self.goodsModel.details addObject:detailImageUrls[i]];
                i++;
            }
        }
    }
    //设置封面
    self.goodsModel.coverImageUrl =self.goodsModel.topRollingImages.firstObject;
    @WeakObj(self);
    [MPublicManager submitListName:self.goodsModel.listName obj:self.goodsModel successfulBlock:^{
        [ZSProgressHUD showSuccessfulAnimatedText:@"发布完成"];
        [selfWeak performSelector:@selector(backItemClicked) withObject:nil afterDelay:1];
    } errorBlock:^(NSString * str) {
        [ZSProgressHUD showDpromptText:@"str"];
    }];
    
}




- (ZLPhotoActionSheet *)getPas
{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
#pragma optional
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    //设置照片最大选择数
    actionSheet.maxSelectCount = 20;
    //单选模式是否显示选择按钮
    actionSheet.showSelectBtn = NO;
    
#pragma required
    //如果调用的方法没有传sender，则该属性必须提前赋值
    actionSheet.sender = [MPublicManager sharedPublicManager].currentControllr;
    @WeakObj(self);
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        [selfWeak selectedContentImages:images];
    }];
    return actionSheet;
}
- (void)selectedContentImages:(NSArray *)images {
    for (UIImage *image in images) {
        ReleaseCellModel *model = [[ReleaseCellModel alloc] init];
        model.showType=Show_Image_Type;
        model.image=image;
        [self.dataArray insertObject:model atIndex:self.dataArray.count-1];
    }
    [_tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
